package babo.cd.physicalexperiment.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.TwoLevelHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.activity.EditDeviceActivity;
import babo.cd.physicalexperiment.activity.HistoryDetailActivity;
import babo.cd.physicalexperiment.app.MyApplication;
import babo.cd.physicalexperiment.bean.MyDevicesListBean;
import babo.cd.physicalexperiment.bean.ShiyanHistoryListBean;
import babo.cd.physicalexperiment.data.MyEnventData;
import babo.cd.physicalexperiment.databinding.FragmentShebeilistBinding;
import babo.cd.physicalexperiment.dialog.DialogCommon;
import babo.cd.physicalexperiment.utils.OKCallback;
import babo.cd.physicalexperiment.utils.OkUtils;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.utils.URLS;
import babo.cd.physicalexperiment.view.RoundAngleImageView;

public class ShiyanHistoryListFragment extends BaseFragment {
    FragmentShebeilistBinding binding;
   int type=0;
   int pi=0;
   BaseQuickAdapter adapter;
   DialogCommon dialogCommon;
   boolean isadmin=true;
   Gson gson;
    List<ShiyanHistoryListBean.RecordData> datas=new ArrayList<>();
    @SuppressLint("ValidFragment")
   public ShiyanHistoryListFragment(int type,boolean isadmin){
       this.type=type;
       this.isadmin=isadmin;
   }
    @Override
    public View getLayout() {
        binding=FragmentShebeilistBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void initView() {
        binding.smr.setRefreshHeader(new TwoLevelHeader(getActivity()));
        binding.smr.setRefreshFooter(new ClassicsFooter(getActivity()));
        binding.smr.setEnableLoadMore(true);
        binding.smr.setEnableRefresh(true);
        binding.rcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter=new BaseQuickAdapter( R.layout.layout_history,datas) {
            @Override
            protected void convert(BaseViewHolder helper, Object item) {
          bindConvert(helper,(ShiyanHistoryListBean.RecordData) item);
            }


        };
        binding.rcv.setAdapter(adapter);
        gson=new Gson();
    }

    private void bindConvert(BaseViewHolder helper, ShiyanHistoryListBean.RecordData item) {
        TextView tx_uname=helper.getView(R.id.tx_name);
        TextView tx_time=helper.getView(R.id.tx_time);
        TextView tx_status=helper.getView(R.id.tx_status);
        TextView tx_device=helper.getView(R.id.tx_device);
        TextView tx_count=helper.getView(R.id.tx_count);
        RelativeLayout rlc=helper.getView(R.id.rlc);
        tx_uname.setText(item.getUserName());
        tx_time.setText(item.getCreateTime());
        String status=item.getExpResult();
        tx_device.setText("实验设备："+item.getDeviceName());
        if (status.equals("2")){
         tx_status.setText("放弃实验");
         tx_status.setTextColor(Color.parseColor("#ff0000"));
        }else{
            tx_status.setText("完成实验");
            tx_status.setTextColor(Color.parseColor("#66cc00"));
        }
        rlc.setOnClickListener(view -> {
            Intent intent=new Intent(getActivity(), HistoryDetailActivity.class);
            intent.putExtra("data",item);
            intent.putExtra("type",type);
            startActivity(intent);
        });
        String ss=item.getExpData();
        try {
        List<ShiyanHistoryListBean.Record> list= gson.fromJson(ss, new TypeToken<List<ShiyanHistoryListBean.Record>>() {}.getType());



            int size=list.size();
            tx_count.setText("实验数据:"+size);
        }catch (Exception ex){
            tx_count.setText("实验数据:0");
        }



    }



    @Override
    public void initData() {
        Out.out("这里的flag==="+type);
        getSheBeiList();
    }

    private void getSheBeiList() {
        String url=URLS.getHistory+"?expId="+type+"&ps=10&pi="+pi;
        if (!isadmin){
            url=url+"&userId="+ MyApplication.getInstance().getUserBaseInfo().getId();
        }
        final String nurl=url;
        Out.out("请求URL=="+url);
        OkUtils.GetOk(url,new OKCallback(getActivity()){
            @Override
            public void Sucess(String str) {

                super.Sucess(str);

                Out.out("实验记录数据："+str);
                Gson gson=new Gson();
                try {
                   binding.smr.finishRefresh(300);
                }catch (Exception e){}
                try {
                    binding.smr.finishLoadMore(300);
                }catch (Exception e){}
                try {
                    ShiyanHistoryListBean myDevicesListBean= JSON.parseObject(str,ShiyanHistoryListBean.class);
                    datas.addAll(myDevicesListBean.getData().getRecords());
                    if (datas.size()>0){
                        binding.rcv.setVisibility(View.VISIBLE);
                        binding.txNodata.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                    }else{
                        if (pi==0){
                            binding.rcv.setVisibility(View.GONE);
                            binding.txNodata.setVisibility(View.VISIBLE);
                        }else{
                            Out.toast(getActivity(),"已加载完所有数据！");
                        }

                    }
                }catch (Exception e){
                    Out.out("报错type"+str);
                    Out.out("报错url"+nurl);

                }

            }
        });
    }

    @Override
    public void setListener() {
        binding.smr.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
             datas.clear();
                pi=0;
             getSheBeiList();
            }
        });
        binding.smr.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
            pi++;
            getSheBeiList();
            }
        });

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MyEnventData message) {
        String msg=message.message;
        if (msg.equals("adddevice")){
//            datas.clear();
//            getSheBeiList();
        }

    }
}
